package org.finalministry.rest.server;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.ws.rs.core.UriBuilder;

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.NetworkListener;
import org.glassfish.grizzly.http.server.StaticHttpHandler;
import org.glassfish.jersey.grizzly2.GrizzlyHttpServerFactory;
import org.glassfish.jersey.media.json.JsonJacksonModule;
import org.glassfish.jersey.server.Application;
import org.glassfish.jersey.server.ResourceConfig;

public class MinimalServerRest {

	private static final String SRC_MAIN_WEBAPP = "resources/WEB-INF/web";

	public static String contentUrl;

	private static final String CONTENT_PATH = "/content";

	public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException {
		final int port = System.getenv("PORT") != null ? Integer.valueOf(System.getenv("PORT")) : 8080;
		final URI baseUri = UriBuilder.fromUri("http://0.0.0.0/").port(port).build();
		final Application application = Application.builder(ResourceConfig.builder().packages(MinimalServerRest.class.getPackage().getName()).build()).build();
		application.addModules(new JsonJacksonModule());
		final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, application);
		httpServer.getServerConfiguration().addHttpHandler(new StaticHttpHandler(SRC_MAIN_WEBAPP), CONTENT_PATH);

		for (NetworkListener networkListener : httpServer.getListeners()) {
			if (System.getenv("FILE_CACHE_ENABLED") == null) {
				networkListener.getFileCache().setEnabled(false);
			}
		}

		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				httpServer.stop();
			}
		});

		contentUrl = System.getenv("CONTENT_URL") != null ? System.getenv("CONTENT_URL") : CONTENT_PATH;

		Thread.currentThread().join();
	}
}
